package com.example.pingze.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.pingze.entity.ID;
import com.example.pingze.entity.PoetInfo;
import com.example.pingze.entity.PoetInfo1;
import com.example.pingze.repository.PoetFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class PoetFileService {
    @Autowired
    private PoetFileRepository repository;

    public List<PoetInfo> fromJson() {
        List<PoetInfo> writerList = new ArrayList<>();
        String json = "C:\\Users\\asus\\Desktop\\chinese-gushiwen\\writer\\02.json";
        File jsonFile = new File(json);
        String jsonData = getJsonStr(jsonFile);
        JSONArray jsonArray = JSONUtil.parseArray(jsonData);
        List<PoetInfo1> writers = JSONUtil.toList(jsonArray,PoetInfo1.class);
        for(PoetInfo1 list : writers){
            PoetInfo poetInfo = getPoetList(list);
            writerList.add(poetInfo);
        }
        return writerList;
    }

    private PoetInfo getPoetList(PoetInfo1 list) {
        PoetInfo poetInfo = new PoetInfo();
        ID id = list.get_id();
        String oid = id.get$oid();
        String name = list.getName();
        String headImageUrl = list.getHeadImageUrl();
        String simpleIntro = list.getSimpleIntro();
        poetInfo.setId(oid);
        poetInfo.setPoetName(name);
        poetInfo.setHeadImageUrl(headImageUrl);
        poetInfo.setSimpleIntro(simpleIntro);
        return poetInfo;
    }

    public String getJsonStr(File file){
        String jsonStr = "";
        try {
            FileReader fileReader = new FileReader(file);
            Reader reader = new InputStreamReader(new FileInputStream(file));
            int ch = 0;
            StringBuffer buffer = new StringBuffer();
            while (((ch = reader.read()) != -1)) {
                buffer.append((char)ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = buffer.toString();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }
    public void insertWriter(List<PoetInfo> list) {
        for(PoetInfo poetInfo : list){
            repository.save(poetInfo);
        }
    }
}
